package com.bjfu.gmms.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

@WebServlet("/logViewer")
public class LogServlet extends HttpServlet {
    private static final int PAGE_SIZE = 10; // 每页显示的日志条数

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageParam = request.getParameter("page");
        int page = (pageParam != null) ? Integer.parseInt(pageParam) : 1;

        // 获取日志数据
        List<String> logs = getLogsForPage(page);
        int totalPages = getTotalPages();

        // 设置请求属性，转发到 JSP
        request.setAttribute("logs", logs);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("currentPage", page);

        request.getRequestDispatcher("/logs.jsp").forward(request, response);
    }

    // 读取日志文件的特定分页内容
    private List<String> getLogsForPage(int pageNumber) {
        List<String> logs = new ArrayList<>();
        File logFile = new File("/Users/lloyd/Desktop/数据库.log");

        try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) {
            String line;
            int startLine = (pageNumber - 1) * PAGE_SIZE;
            int endLine = pageNumber * PAGE_SIZE;
            int currentLine = 0;

            while ((line = reader.readLine()) != null) {
                if (currentLine >= startLine && currentLine < endLine) {
                    logs.add(line);
                }
                currentLine++;
                if (currentLine >= endLine) break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return logs;
    }

    // 获取日志文件的总页数
    private int getTotalPages() {
        int totalLines = 0;
        File logFile = new File("/Users/lloyd/Desktop/数据库.log");

        try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) {
            while (reader.readLine() != null) {
                totalLines++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (int) Math.ceil((double) totalLines / PAGE_SIZE);
    }
}